package com.cml.rpc.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 服务端实现类
 * @author cml
 * @create 2021/7/20 17:45
 */
public class SimpleRpcServer implements RpcServer {

    // 服务提供者
    private Map<String, Object> serviceProvide;
    // 线程池,用线程池代替new Thread
    private ThreadPoolExecutor threadPoolExecutor;

    public SimpleRpcServer(Map<String, Object> serviceProvide) {
        this.serviceProvide = serviceProvide;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(),
                16, 60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5));
        this.threadPoolExecutor = threadPoolExecutor;
    }

    public SimpleRpcServer(Map<String, Object> serviceProvide, int corePoolSize, int maximumPoolSize,
                           long keepAliveTime, TimeUnit unit,
                           BlockingQueue<Runnable> workQueue) {
        this.serviceProvide = serviceProvide;
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        this.threadPoolExecutor = threadPoolExecutor;
    }

    @Override
    public void start(int port) {
        System.out.println("------使用simple服务端------");
        ServerSocket serverSocket = getServerSocket(port);
        if (serverSocket != null) {
            while (true) {
                try {
                    Socket accept = serverSocket.accept();
                    System.out.println("--------------");
                    threadPoolExecutor.execute(new WorkThread(accept,serviceProvide));
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("accept发送IO异常");
                }
            }
        }
    }

    @Override
    public void stop() {

    }

    private ServerSocket getServerSocket(int port) {
        ServerSocket serverSocket = null;
        System.out.println("服务端启动....");
        try {
             serverSocket = new ServerSocket(port);
             return serverSocket;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务端启动失败");
        }
        return null;
    }
}
